package com.zlq.cn.service.exam;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zlq.cn.entity.ExamAnswers;
import com.zlq.cn.entity.ExamQuestions;
import com.zlq.cn.mapper.exam.ExamQuestionsMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import one.util.streamex.StreamEx;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhoucl
 * @since 2024-04-10
 */
@Service
public class ExamQuestionsService extends ServiceImpl<ExamQuestionsMapper, ExamQuestions> {

    @Resource
    private ExamAnswersService examAnswersService;

    public List<ExamQuestions> bindAnswers(List<ExamQuestions> examQuestionsList, ExamQuestions examQuestions) {
        LambdaQueryChainWrapper<ExamAnswers> query = examAnswersService.lambdaQuery();
        if (examQuestionsList != null) {
            if (examQuestionsList.isEmpty()) {
                return examQuestionsList;
            } else {
                query.in(ExamAnswers::getQuestionId, StreamEx.of(examQuestionsList).map(ExamQuestions::getQuestionId).toSet());
            }
        } else {
            examQuestionsList = super.lambdaQuery()
                    .eq(Objects.nonNull(examQuestions.getChapterId()), ExamQuestions::getChapterId, examQuestions.getChapterId())
                    .list();
        }
        Map<Integer, List<ExamAnswers>> examAnswersQuestionMap = query.list().stream().collect(Collectors.groupingBy(ExamAnswers::getQuestionId));
        for (ExamQuestions examQuestion : examQuestionsList) {
            examQuestion.setExamAnswers(examAnswersQuestionMap.get(examQuestion.getQuestionId()));
        }
        return examQuestionsList;
    }
}
